<template>
  <div>
    <div class="search-bar">
      <form action="/">
        <van-search
          v-model="inputKeyword"
          show-action
          :placeholder="placeholder"
          @input="onInput"
          @search="onSearch"
          @clear="onClear"
          @cancel="onCancel"
        />
      </form>
    </div>

    <template v-if="searchResultHidden">
      <template v-if="suggests === null">
        <search-hotword
          :hotwords="hotwords"
          @tag-click="openSearchResult"
        />
        <search-history
          :historys="historys"
          @select="openSearchResult"
          @clear="clearHistory"
        />
      </template>
      <template v-else>
        <search-suggest
          :suggests="suggests"
          @suggest-click="openSearchResult"
        />
      </template>
    </template>
    <template v-else>
      <search-result
        :keyword="searchKeyword"
      />
    </template>
  </div>
</template>

<script>
import { Search as VanSearch } from 'vant'
import SearchHotword from '@/components/search/SearchHotword.vue'
import SearchSuggest from '@/components/search/SearchSuggest.vue'
import SearchHistory from '@/components/search/SearchHistory.vue'
import SearchResult from '@/components/search/SearchResult.vue'
import { apiGetDefaultKey, apiGetHotSearchKey, apiGetSearchSuggest } from '@/api/search.js'
import { setStorage, getStorage, removeStorage } from '@/utils/localStorage.js'
export default {
  name: 'Search',
  components: {
    VanSearch,
    SearchHotword,
    SearchSuggest,
    SearchHistory,
    SearchResult
  },
  inject: ['rootRouter', 'rootTitle', 'rootKeyword', 'rootDescription'],
  metaInfo () {
    return {
      title: `搜索-${this.rootTitle}`,
      meta: [
        { name: 'keywords', content: this.rootKeyword },
        { name: 'description', content: this.rootDescription }
      ]
    }
  },
  props: {
    keyword: {
      type: String
    }
  },
  data () {
    return {
      inputKeyword: this.keyword,
      searchKeyword: this.keyword,
      placeholder: '请输入搜索关键词',
      defaultSearch: null,
      searchSuggests: null,
      searchTimeout: null,
      hotwords: [],
      suggests: null,
      historys: []
    }
  },
  computed: {
    searchResultHidden () {
      return !this.searchKeyword
    }
  },
  watch: {
    keyword (newVal) {
      this.searchKeyword = newVal
      this.inputKeyword = newVal
    },
    searchResultHidden: {
      immediate: true,
      handler (newVal) {
        if (newVal) {
          this.getHotSearchKey()
        }
      }
    }
  },
  created () {
    this.getSearchDefault()
    this.historys = getStorage('search_history')
  },
  methods: {
    getSearchDefault () {
      apiGetDefaultKey().then(res => {
        const { data, code } = res
        if (code === 0 && data !== null) {
          this.defaultSearch = data
          this.placeholder = data.show_name
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getHotSearchKey () {
      apiGetHotSearchKey().then(res => {
        const { list, code } = res
        if (code === 0 && list !== null) {
          this.hotwords = list.slice(0, 8)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    onInput (value) {
      this.searchKeyword = ''
      if (value) {
        this.suggests = []
        if (this.searchTimeout) {
          clearTimeout(this.searchTimeout)
        }
        this.searchTimeout = setTimeout(() => {
          apiGetSearchSuggest({ term: value }).then(res => {
            const { result, code } = res
            if (code === 0 && Object.prototype.toString.call(result) === '[object Object]') {
              const time = new Date().getTime()
              const newTags = result.tag.map((item, index) => {
                item.key = time + index
                return item
              })
              this.suggests = newTags
            } else {
              this.suggests = []
            }
          }).catch(err => {
            console.log(err)
            this.suggests = []
          })
        }, 300)
      } else {
        this.suggests = null
      }
    },
    onSearch (value) {
      if (value) {
        this.openSearchResult(value)
      } else {
        const goType = this.defaultSearch.go_type
        if (goType === 1) {
          // 直接跳转视频详情页
          const url = this.defaultSearch.url
          const bvid = url.replace(/.*(BV.+)/g, '$1')
          this.rootRouter.push({ name: 'video', params: { bvid } })
        }
      }
    },
    onClear () {
      this.openSearchResult('')
    },
    onCancel () {
      this.rootRouter.push({ path: '/' })
    },
    openSearchResult (keyword) {
      this.suggests = null
      keyword && this.setHistory(keyword)
      this.rootRouter.push({ path: 'search', query: { keyword: keyword } })
    },
    setHistory (value) {
      const vals = getStorage('search_history')
      const matchIndex = vals.findIndex(val => val.value === value)
      if (matchIndex === -1) {
        const item = {
          value,
          isHistory: 1,
          timestamp: new Date().getTime()
        }
        this.historys.unshift(item)
        setStorage('search_history', this.historys)
      }
    },
    clearHistory () {
      removeStorage('search_history')
      this.historys = []
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-bar{
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: $color-white;
    .van-search__action{
      color: $theme-color;
    }
  }
</style>
